package com.zs.service.impl;

import com.zs.common.exception.BusinessException;
import com.zs.common.model.DemoUser;
import com.zs.common.transform.DemoUserTransformer;
import com.zs.common.dto.DemoUserDTO;
import com.zs.dao.repository.DemoUserRepository;
import com.zs.service.DemoUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.Serializable;

/**
 * Copyright 2020 ZS Network Co., Ltd. All rights reserved.
 * 本文件仅限于正数网络技术有限公司内部传阅，禁止外泄以及用于其他的商业目的。
 * Created by yuancong on 2022-12-02.
 */
@Service
@Slf4j
public class DemoUserServiceImpl implements DemoUserService {
    @Autowired
    private DemoUserRepository demoUserRepository;
    @Autowired
    private DemoUserTransformer demoUserTransformer;

    @Override
    public DemoUserDTO get(Serializable id) {
        DemoUser entity = demoUserRepository.getById(id);
        Assert.notNull(entity,"record not found");
        return demoUserTransformer.toDTO(entity);
    }

    @Override
    public boolean insert(DemoUserDTO record) {
        if (record == null) {
            throw new IllegalStateException("参数record不能为空");
        }
        if(StringUtils.isEmpty(record.getCode())){
            log.info("param:{}",record);
            throw new BusinessException("");
        }

        return demoUserRepository.save(demoUserTransformer.fromDTO(record));
    }

    @Override
    public boolean update(DemoUserDTO record) {
        if (record == null) {
            throw new IllegalStateException("参数record不能为空");
        }

        return demoUserRepository.updateById(demoUserTransformer.fromDTO(record));
    }

    @Override
    public Page<DemoUserDTO> pageList(Integer pageNum, Integer pageSize) {
        Page<DemoUser> demoUserPage = new Page<>(pageNum,pageSize);
        Page<DemoUserDTO> resultPage = new Page<>();
        demoUserPage = demoUserRepository.page(demoUserPage);
        BeanUtils.copyProperties(demoUserPage,resultPage);
        resultPage.setRecords(demoUserTransformer.toDTOList(demoUserPage.getRecords()));
        return resultPage;
    }
}
